package setting

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/core/response"
	"likeadmin/dao"
	"likeadmin/util"
)

type IUserService interface {
	Get(c *gin.Context) (res resp.UserSetResp, e error)
	Set(c *gin.Context, req req.UserSetReq) (e error)
}

// NewUserService 初始化
func NewUserService(db *gorm.DB, dao *dao.Query) IUserService {
	return &userService{db: db, dao: dao}
}

// userService 系统管理员服务实现类
type userService struct {
	db  *gorm.DB
	dao *dao.Query
}

// Get 用户设置
func (srv userService) Get(c *gin.Context) (res resp.UserSetResp, e error) {
	str, err := util.ConfigUtil.GetVal(srv.db, "user", "defaultAvatar", "/api/static/default_avatar.png")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}
	res.DefaultAvatar = str
	res.DefaultAvatar = util.UrlUtil.ToAbsoluteUrl(res.DefaultAvatar)
	return
}

// Set 设置用户配置
func (srv userService) Set(c *gin.Context, req req.UserSetReq) (e error) {
	path := util.UrlUtil.ToRelativeUrl(req.DefaultAvatar)
	err := util.ConfigUtil.Set(srv.db, "user", "defaultAvatar", path)
	if e = response.CheckErr(err, "Save Set name err"); e != nil {
		return
	}

	// 清空缓存
	util.RedisUtil.HDel("user", "defaultAvatar")
	return
}
